package com.filter;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.common.DateEditor;
import com.common.EmiJsonObj;

public class BaseController {
	@Autowired  
	private  HttpServletResponse response;
	
	@Autowired
	private HttpServletRequest req;

	public HttpServletRequest getReq() {
		return req;
	}
	
	public HttpServletResponse getResponse(){
		return response;
	}
	
	@InitBinder    
	public void initBinder(WebDataBinder binder) {   
		binder.registerCustomEditor(Date.class, new DateEditor());
	}
	
	public void responseJson(Object o){
		try {
			req.setCharacterEncoding("utf-8");
			response.setContentType("application/json;charset=utf-8");
			
			response.getWriter().write(EmiJsonObj.fromObject(o).toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void responseJsonArray(Object o){
		try {
			req.setCharacterEncoding("utf-8");
			response.setContentType("application/json;charset=utf-8");
			
			response.getWriter().write(EmiJsonObj.fromArray(o).toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void responseText(String o){
		try {
			req.setCharacterEncoding("utf-8");
			response.setContentType("text/plain;charset=utf-8");
			
			response.getWriter().write(o);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
